package demos;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: lzp
 * @description: 自用对象工具类，不使用在业务中，方便开发中一些操作
 * @Date: 2022/7/25
 */
public class FieldUtils {

    public static Pattern PATTERN_HUMP_TO_CASE = Pattern.compile("[A-Z]");
    public static Pattern PATTERN_CASE_TO_HUMP = Pattern.compile("[A-Z]");

    /**
     * 获取传入对象，下划线风格的所有私有字段
     *
     * @param clazz 对象的字节码
     */
    public static List<String> getFieldsToCase(Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        List<String> list = new ArrayList<>();
        for (Field field : fields) {
            // 将字段名称转换为下划线风格
            list.add(humpToCase(field.getName()));
        }
        return list;
    }

    /**
     * @Description 将驼峰转为下划线 underline
     */
    public static String humpToCase(String str) {
        Matcher matcher = PATTERN_HUMP_TO_CASE.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * @Description 将下划线转为驼峰
     */
    public static String caseToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = PATTERN_CASE_TO_HUMP.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(0).toUpperCase().replace("_", ""));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

}
